package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdUserMapper;
import com.heima.admin.service.AdUserService;
import com.heima.common.exception.CustException;
import com.heima.model.admin.dtos.AdUserDto;
import com.heima.model.admin.dtos.ResponseResult;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.admin.vos.AdUserVO;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import java.lang.reflect.InvocationTargetException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description:
 * @Version: V1.0
 */
@Service
public class AdUserServiceImpl extends ServiceImpl<AdUserMapper, AdUser> implements AdUserService {
    /**
     * admin 登录
     *
     * @param dto
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public ResponseResult login(AdUserDto dto)  {
        //1 参数校验
        if (dto == null || StringUtils.isBlank ( dto.getName () ) || StringUtils.isBlank ( dto.getPassword () )) {
            return ResponseResult.errorResult ( AppHttpCodeEnum.PARAM_INVALID, "用户名或者密码不能为空" );
        }
        //2 根据用户名查询用户信息
        AdUser adUser = getOne ( Wrappers.<AdUser>lambdaQuery ().eq ( AdUser::getName, dto.getName () ) );
        if (adUser == null) {
            CustException.cust ( AppHttpCodeEnum.DATA_NOT_EXIST, "用户不存在" );
        }
        //3 获取数据库密码和盐， 匹配密码
        String inputPwd = DigestUtils.md5DigestAsHex ( (dto.getPassword () + adUser.getSalt ()).getBytes () );
        if (!inputPwd.equals ( adUser.getPassword () )) {
            CustException.cust ( AppHttpCodeEnum.LOGIN_PASSWORD_ERROR );
        }

        if (adUser.getStatus ().intValue () != 9) {
            CustException.cust ( AppHttpCodeEnum.DATA_NOT_ALLOW, "用户状态异常" );
        }
        //4 修改登录时间
        adUser.setLoginTime ( new Date () );
        updateById ( adUser );

        //5 颁发token jwt 令牌
        String token = AppJwtUtil.getToken ( adUser.getId ().longValue () );
        // 用户信息返回 VO
        AdUserVO userVO = new AdUserVO ();
//        userVO.setId(adUser.getId());
//        userVO.setEmail(adUser.getEmail());
        BeanUtils.copyProperties ( adUser, userVO );
        //6 返回结果（jwt）
        Map map = new HashMap ();
        map.put ( "token", token );
        map.put ( "user", userVO );
        return ResponseResult.okResult ( map );
    }

    @Override
    public ResponseResult register(AdUser user) {
        //1.参数校验
        if (StringUtils.isEmpty ( user.getName () )
                || StringUtils.isEmpty ( user.getPassword () )) {
            return ResponseResult.errorResult ( AppHttpCodeEnum.PARAM_INVALID, "用户名或密码不能为空" );
        }
        // 业务处理
        // 用户的密码加密规则是：MD5（密码 + salt）
        String salt = RandomStringUtils.randomAlphanumeric ( 8 );
        String password = user.getPassword ();
        user.setPassword ( DigestUtils.md5DigestAsHex ( (password + salt).getBytes () ) );
        user.setSalt ( salt );
        user.setCreatedTime ( new Date () );
        user.setStatus ( 9 );
        save ( user );
        return ResponseResult.okResult ( AppHttpCodeEnum.SUCCESS );
    }
}
